<template>
  <div class="order-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="我的订单" left-text="返回" fixed left-arrow @click-left="$router.back()" />
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <div class="order-content">
        <div class="title-content">
          <div class="title">我的订单</div>
          <div class="is-link" @click="$router.push('/all/order')">全部<van-icon name="arrow" /></div>
        </div>
        <van-tabs v-model="status" animated @change="changeHandler">
          <van-tab v-for="index in titles.length" :key="index" :title="titles[index - 1]">
            <!-- 订单信息 -->
            <van-empty description="没有订单数据" v-if="orderGoodsList.length == 0" />
            <van-list offset="0" v-else :immediate-check="false" v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
              <div class="order-content-item" v-for="item in orderGoodsList" :key="item.oid">
                <div class="order-info">
                  <span class="title">订单信息</span>
                  <van-button v-if="item.status === 0" round type="primary" size="mini" color="linear-gradient(to right,#ffd01e,#ff8917)" @click="$router.push('/order/payment/' + item.orderId)">去支付</van-button>
                </div>
                <div class="order-number">
                  <span>订单编号：{{ item.orderId }}</span>
                  <!-- 待支付订单显示 -->
                  <span v-if="item.status == 0">
                    <van-button round type="primary" size="mini" color="#F01226" @click="deleteOrder(item)">取消订单</van-button>
                  </span>
                  <!-- 待发货订单显示 -->
                  <span v-else-if="item.status == 1"><van-button round type="primary" size="mini" color="#F01226" disabled>待发货</van-button></span>
                  <!-- 待收货订单显示 -->
                  <span v-else-if="item.status == 2"><van-button round type="primary" size="mini" color="#F01226" @click="receipt(item)">收货</van-button></span>
                  <!-- 已经完成的订单显示 -->
                  <span v-else-if="item.status == 3"><van-button round type="primary" size="mini" color="#F01226" @click="deleteOrder(item)">删除订单</van-button></span>
                </div>
                <div class="goods-list">
                  <GoodsItemCom :goods_info="item.goodsList"></GoodsItemCom>
                </div>
              </div>
            </van-list>
          </van-tab>
        </van-tabs>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script>
import axios from '@/utils/request/request.js'
import GoodsItemCom from './GoodsItemCom.vue'
import { Notify, Dialog } from 'vant'
export default {
  name: 'allOrderList',
  data() {
    return {
      status: 0,
      page: 1,
      limit: 10,
      titles: ['待支付', '待发货', '待收货', '已完成'],
      orderGoodsList: [],
      loading: false,
      finished: false,
      isLoading: false
    }
  },
  components: { GoodsItemCom },
  methods: {
    deleteOrder(item) {
      // 删除订单
      let title = '删除订单'
      let message = '确定要删除订单吗？'
      if (item.status === 0) {
        title = '取消订单'
        message = '确定要取消订单吗？'
      }
      Dialog.confirm({
        title,
        message
      })
        .then(async () => {
          this.$toast.loading({
            message: '加载中...',
            duration: 0
          })
          try {
            const data = await axios.post('/user/del/order', {
              orderId: item.orderId
            })
            if (data.code === 0) {
              Notify({
                type: 'success',
                message: data.msg,
                duration: 1000
              })
              // 删除成功
              this.orderGoodsList = this.orderGoodsList.filter((order) => order.orderId !== item.orderId)
            } else if (data.code === 403 || data.msg === '身份验证失败') {
              Notify({
                type: 'danger',
                message: data.msg,
                duration: 1000,
                onClose: () => {
                  localStorage.removeItem('user_token')
                  this.$router.replace('/login')
                }
              })
            } else {
              Notify({
                type: 'danger',
                message: data.msg,
                duration: 1000
              })
            }
          } catch {
            Notify({
              type: 'danger',
              message: '取消订单失败！',
              duration: 1000
            })
          } finally {
            this.$toast.clear()
          }
        })
        .catch(() => {})
    },
    receipt(item) {
      Dialog.confirm({
        title: '确认收货',
        message: '您确保您已经收到商品了吗？',
        confirmButtonText: '我已收到',
        cancelButtonText: '未收到'
      })
        .then(async () => {
          try {
            const data = await axios.post('/user/order/receipt', {
              orderId: item.orderId
            })
            if (data.code === 0) {
              // 删除成功
              Notify({
                type: 'success',
                message: data.msg,
                duration: 1000
              })
              item.status = 3
            } else if (data.code === 403 || data.msg === '身份验证失败') {
              Notify({
                type: 'danger',
                message: data.msg,
                duration: 1000,
                onClose: () => {
                  localStorage.removeItem('user_token')
                  this.$router.replace('/login')
                }
              })
            } else {
              Notify({
                type: 'danger',
                message: data.msg,
                duration: 1000
              })
            }
          } catch {
            Notify({
              type: 'danger',
              message: '订单收货提交失败！',
              duration: 1000
            })
          } finally {
            this.$toast.clear()
          }
        })
        .catch(() => {})
    },
    // 切换查看商品订单数据
    changeHandler() {
      this.page = 1
      this.finished = false
      this.orderGoodsList = []
      this.getOrdersByStatus()
    },
    // 根据状态获取订单数据
    async getOrdersByStatus() {
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      try {
        const data = await axios.get('/user/get/orders/status', {
          params: {
            status: this.status,
            page: this.page,
            limit: this.limit
          }
        })
        if (data.code === 0) {
          const orderData = data.data
          if (orderData.length < this.limit) {
            this.finished = true
          }
          const dataList = []
          for (let i = 0; i < orderData.length; i++) {
            if (dataList.length === 0) {
              dataList.push({
                orderId: orderData[i].order_id,
                status: orderData[i].order_status,
                goodsList: [
                  {
                    goods_count: orderData[i].goods_count,
                    goods_img: orderData[i].goods_img,
                    goods_price: orderData[i].goods_price,
                    id: orderData[i].id,
                    goods_name: orderData[i].goods_name,
                    create_time: orderData[i].create_time
                  }
                ]
              })
            } else {
              dataList.some((item, index) => {
                if (item.orderId === orderData[i].order_id) {
                  item.goodsList.push({
                    goods_count: orderData[i].goods_count,
                    goods_img: orderData[i].goods_img,
                    goods_price: orderData[i].goods_price,
                    id: orderData[i].id,
                    goods_name: orderData[i].goods_name,
                    create_time: orderData[i].create_time
                  })
                  return
                }
                if (index === dataList.length - 1 && item.orderId !== orderData[i].order_id) {
                  dataList.push({
                    orderId: orderData[i].order_id,
                    status: orderData[i].order_status,
                    goodsList: [
                      {
                        goods_count: orderData[i].goods_count,
                        goods_img: orderData[i].goods_img,
                        goods_price: orderData[i].goods_price,
                        id: orderData[i].id,
                        goods_name: orderData[i].goods_name,
                        create_time: orderData[i].create_time
                      }
                    ]
                  })
                }
              })
            }
          }
          this.orderGoodsList = [...this.orderGoodsList, ...dataList]
        } else if (data.code === 403 || data.msg === '身份认证错误') {
          Notify({
            type: 'danger',
            duration: 1000,
            message: data.msg,
            onClose: () => {
              localStorage.removeItem('user_token')
              this.$router.replace('/login')
            }
          })
        } else {
          Notify({
            type: 'danger',
            duration: 1000,
            message: data.msg
          })
        }
      } catch {
        Notify({
          type: 'danger',
          duration: 1000,
          message: '请求订单数据失败!'
        })
      } finally {
        this.isLoading = false
        this.loading = false
        this.$toast.clear()
      }
    },
    // 加载更多
    onLoad() {
      this.page++
      this.getOrdersByStatus()
    },
    // 刷新
    onRefresh() {
      this.page = 1
      this.orderGoodsList = []
      this.getOrdersByStatus()
    }
  },
  created() {
    this.getOrdersByStatus()
  }
}
</script>

<style lang="less" scoped>
.order-container {
  background-color: #f5f5f5;
  padding: 46px 10px 5px;
  min-height: 100vh;

  .order-content-item {
    padding: 10px;
    margin-bottom: 15px;
    background-color: white;

    .order-info {
      padding: 10px 0;
      display: flex;
      align-items: center;
      justify-content: space-between;

      span.title {
        color: #444;
        font-size: 14px;
        font-weight: 700;
      }

      ::v-deep .van-button--mini {
        padding: 0 10px;
      }
    }

    .order-number {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 5px;

      span {
        font-size: 14px;
        white-space: nowrap;

        &:first-child {
          font-size: 12px;
          padding: 0 5px;
        }
      }
      ::-webkit-scrollbar {
        display: none;
      }
    }

    ::v-deep .right-circle {
      right: -20px !important;
    }
    ::v-deep .left-circle {
      left: -20px !important;
    }
  }

  .order-content {
    margin-top: 10px;

    .title-content {
      display: flex;
      padding: 10px 10px 0;
      align-items: center;
      justify-content: space-between;
      background-color: #fff;
      border-top-left-radius: 15px;
      border-top-right-radius: 15px;

      .title {
        color: #000;
        font-size: 14px;
        font-weight: 700;
      }
      .is-link {
        color: #969799;
        font-size: 12px;
      }

      ::v-deep .van-icon {
        color: #969799;
      }
    }
    ::v-deep .van-tabs__content {
      margin-top: 10px;
    }
    ::v-deep.van-tabs__line {
      background-color: #ee0a24;
    }
  }

  ::v-deep .van-nav-bar__text,
  ::v-deep .van-icon {
    color: #323232;
  }
}
</style>
